import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, Space, message } from 'antd';
import { FolderOpenOutlined, KeyOutlined } from '@ant-design/icons';
import '../utils/electronMock';

interface SettingsModalProps {
  visible: boolean;
  onClose: () => void;
}

// 确保类型可用
declare global {
  interface Window {
    electronAPI?: {
      selectDirectory: () => Promise<string>;
      getConfig: () => Promise<any>;
      saveConfig: (config: any) => Promise<boolean>;
    };
  }
}

interface SettingsForm {
  apiKey: string;
  watchDirectory: string;
}


const SettingsModal: React.FC<SettingsModalProps> = ({ visible, onClose }) => {
  const [form] = Form.useForm<SettingsForm>();
  const [loading, setLoading] = useState(false);

  // 加载配置
  const loadConfig = async () => {
    try {
      let config = { apiKey: '', watchDirectory: '' };

      if (window.electronAPI && window.electronAPI.getConfig) {
        // 统一使用electronAPI加载配置
        config = await window.electronAPI.getConfig();
      } else {
        // 备用方案：从localStorage读取
        const savedConfig = localStorage.getItem('picshare-config');
        if (savedConfig) {
          config = JSON.parse(savedConfig);
        }
      }

      // 设置表单值
      form.setFieldsValue({
        apiKey: config.apiKey || '',
        watchDirectory: config.watchDirectory || ''
      });
    } catch (error) {
      console.error('加载配置失败:', error);
    }
  };

  useEffect(() => {
    if (visible) {
      loadConfig();
    }
  }, [visible]);

  const handleSelectDirectory = async () => {
    try {
      if (window.electronAPI && window.electronAPI.selectDirectory) {
        // Electron环境 - 真实的目录选择
        const directory = await window.electronAPI.selectDirectory();
        if (directory) {
          form.setFieldsValue({ watchDirectory: directory });
        }
      } else {
        // 开发环境 - 模拟目录选择
        const mockPath = prompt('开发环境模拟：请输入要监听的目录路径\n\n例如：\n• macOS: /Users/用户名/Pictures\n• Windows: C:\\Users\\用户名\\Pictures\n• Linux: /home/用户名/Pictures', '/Users/username/Pictures');
        if (mockPath) {
          form.setFieldsValue({ watchDirectory: mockPath });
          message.info('开发环境：目录路径已设置（生产环境将弹出真实选择器）');
        }
      }
    } catch (error) {
      message.error('选择目录失败');
    }
  };

  const handleSave = async (values: SettingsForm) => {
    setLoading(true);
    try {
      if (window.electronAPI && window.electronAPI.saveConfig) {
        // 统一使用electronAPI保存（开发环境和生产环境）
        const success = await window.electronAPI.saveConfig(values);

        if (success) {
          message.success('设置保存成功');
          onClose();
        } else {
          message.error('保存设置失败');
        }
      } else {
        // 备用方案：直接保存到localStorage
        localStorage.setItem('picshare-config', JSON.stringify(values, null, 2));
        message.success('设置保存成功（开发环境：请下载config.json文件到项目根目录）');
        onClose();
      }
    } catch (error) {
      console.error('保存设置失败:', error);
      message.error('保存设置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onClose();
  };

  return (
    <Modal
      title="设置"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={500}
      centered
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSave}
      >
        <Form.Item
          name="apiKey"
          label="API Key"
        >
          <Input.Password
            prefix={<KeyOutlined />}
            placeholder="请输入API Key（可选）"
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="watchDirectory"
          label="监听目录"
        >
          <Input
            prefix={<FolderOpenOutlined />}
            placeholder="请输入或选择监听目录（可选）"
            size="large"
            suffix={
              <Button
                type="text"
                icon={<FolderOpenOutlined />}
                onClick={handleSelectDirectory}
                title="选择目录"
              />
            }
          />
        </Form.Item>

        <Form.Item style={{ marginBottom: 0 }}>
          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={handleCancel}>
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
            >
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SettingsModal;